import { phoneEncryption } from '../../../utils/util';
import { request } from '../../../utils/request';
import { api } from '../../../config/api';
import Toast from 'tdesign-miniprogram/toast/index';
const app = getApp();

Page({
	data: {
		personInfo: {
			avatarUrl: '',
			nickName: '',
			gender: 0,
			phoneNumber: '',
		},
		showUnbindConfirm: false,
		pickerOptions: [
			{
				name: '男',
				code: '1',
			},
			{
				name: '女',
				code: '2',
			},
		],
		typeVisible: false,
		genderMap: ['', '男', '女'],
	},
	onLoad() {
		this.init();
	},
	init() {
		this.fetchData();
	},
	fetchData() {
		request.get(api.user.my, {}).then(res => {
			const { userInfo } = res;
			this.setData({
				personInfo: userInfo,
				'personInfo.phoneNumber': phoneEncryption(userInfo.phoneNumber)
			});
		});
	},
	onClickCell({ currentTarget }) {
		const { dataset } = currentTarget;
		const { nickName } = this.data.personInfo;

		switch (dataset.type) {
			case 'gender':
				this.setData({
					typeVisible: true,
				});
				break;
			case 'name':
				wx.navigateTo({
					url: `/pages/usercenter/name-edit/index?name=${nickName}`,
				});
				break;
			case 'avatarUrl':
				this.toModifyAvatar();
				break;
			default: {
				break;
			}
		}
	},
	onClose() {
		this.setData({
			typeVisible: false,
		});
	},
	onConfirm(e) {
		const { value } = e.detail;
		const me = this;
		me.setData({
			typeVisible: false,
			'personInfo.gender': value,
		});
		wx.showLoading({
			title: '处理中',
			mask: true,
		});
		request.post(api.user.edit, { gender: value }).then((res) => {
			wx.hideLoading();
			Toast({
				context: me,
				selector: '#t-toast',
				message: '设置成功',
				theme: 'success',
			});
		});
	},
	async toModifyAvatar() {
		try {
			const tempFilePath = await new Promise((resolve, reject) => {
				wx.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const { path, size } = res.tempFiles[0];
						if (size <= 10485760) {
							resolve(path);
						} else {
							reject({ errMsg: '图片大小不能超过10M' });
						}
					},
					fail: (err) => reject(err),
				});
			});
			const token = wx.getStorageSync("token");
			// 上传当前图片
			const me = this;
			wx.showLoading({
				title: '上传中',
			});
			wx.uploadFile({
				url: api.user.uploadHeader,
				filePath: tempFilePath,
				name: 'file',
				header: {
					"Authorization": `Bearer ${token}`,
					"Content-Type": "application/json"
				},
				success: function (res) {
					let data = JSON.parse(res.data);
					request.post(api.user.edit, { header: data.data.src })
						.then(res => {
							me.setData({ 'personInfo.avatarUrl': data.data.src });
							wx.hideLoading();
						}).catch(() => {
							wx.hideLoading();
						});
				},
				fail: function (error) {
					console.log('头像上传失败：', error);
					wx.hideLoading();
					Toast({
						context: this,
						selector: '#t-toast',
						message: `上传失败`,
						theme: 'success',
					});
				}
			});

		} catch (error) {
			if (error.errMsg === 'chooseImage:fail cancel') return;
			Toast({
				context: this,
				selector: '#t-toast',
				message: error.errMsg || error.msg || '修改头像出错了',
				theme: 'error',
			});
		}
	},
	openUnbindConfirm() {
		wx.showLoading({
			title: '处理中',
			mask: true,
		});
		wx.removeStorageSync('token');
		app.globalData.isLogin = false;
		setTimeout(() => {
			wx.hideLoading();
			wx.navigateTo({
				url: '/pages/login/index',
			});
		}, 500);
	},
});
